package com.dycong.common.IO.socket.AIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;

/**
 * Created by dycong on 2017/3/26.
 */
public class AIOServer {

    private static int PORT = 12121;
    private static String HOST = "172.0.0.1";
    //@see 多线程共享一个AsynchronousServerSocketChannel，不能重复监听同一个端口，设为静态线程共享爱那个，不可修改
    private static AsynchronousServerSocketChannel serverSocketChannel;

    public AIOServer() {
    }

    public AIOServer(String host, Integer port) {
        PORT = port;
        HOST = host;
    }

    public void start() {
        start(HOST, PORT);
    }

    //一般用到的是1到65535，其中0不使用,一般的应用程序使用1024到4999用来通讯,5000以后的用来用户自定义端口
    private void start(String host, Integer port) {
        try {
            if (serverSocketChannel == null) {
                if (host != null & host.length() != 0 & port != null & port > 0 & port < 65535) {
                    synchronized (host + port) {
                        if (null == serverSocketChannel) {
                            serverSocketChannel = AsynchronousServerSocketChannel.open();
                            serverSocketChannel.bind(new InetSocketAddress(host, port));
                        }
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("server start error: " + e);
        }


    }
}
